/*
 * Copyright TLR Team, Inc. All Rights Reserved.
 */
package com.tlr.device.service;

import com.tfb.service.utility.AppConst;
import com.tfb.service.utility.JsonUtil;
import com.tfb.service.utility.HttpUtil;
import com.tfb.service.utility.MD5Util;
import com.tfb.service.utility.Utils;
import com.tlr.device.model.LocationCard;
import java.io.IOException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonNode;

public class LocationDevice implements AppConst {

    private static final Logger log = Logger.getLogger(LocationDevice.class);

    public String getLocateDeviceUrl(String ecid, String msisdn, String transid) {
        return String.format(DEVICE_SERVICE_URL, ecid, msisdn, transid, MD5Util.MD5(ecid + transid + msisdn));
    }

    public String getLocationDeviceJson(String ecid, String msisdn) throws IOException {
        try (CloseableHttpClient httpClient = HttpUtil.createHttpClient()) {
            String localDeviceUrl = getLocateDeviceUrl(ecid, msisdn, Long.toString(System.currentTimeMillis()) + Long.toString((long) Math.floor(Math.random() * 100000)));
            log.info("URL:" + localDeviceUrl);
            HttpGet httpGet = new HttpGet(localDeviceUrl);
            try (CloseableHttpResponse localDeviceResp = httpClient.execute(httpGet)) {
                String devceListJsonStr = EntityUtils.toString(localDeviceResp.getEntity(), JsonUtil.UTF8);
                return devceListJsonStr;
            }
        }
    }

    public LocationCard getLocationDevice(String ecid, String msisdn) throws IOException {
        LocationCard lc = new LocationCard();
        try {
            String locationJsonStr = this.getLocationDeviceJson(ecid, msisdn);
            JsonNode locationNode = JsonUtil.createJson(locationJsonStr);
            if (locationNode.get("status").getIntValue() != 1) {
                log.error("This device can't be seached");
                log.error(locationJsonStr);
                //throw new RuntimeException("Error: " + locationNode.get("message"));
                lc.setEnable(false);
                lc.setStatus(0);
                return lc;
            }
            lc.setEnable(true);
            lc.setStatus(1);
            JsonNode result = locationNode.get("result");
            lc.setLng(result.get("lng").getTextValue());
            lc.setLat(result.get("lat").getTextValue());
        } catch (Exception e) {
            lc.setEnable(false);
            lc.setStatus(0);
            log.error(Utils.getFullException(e));
        }
        return lc;
    }
}
